package com.sysware.p2m.jgit;

import java.io.File;
import java.io.IOException;

import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

public class P2MGitClient {

	private String remoteGitUrl;
	private String branch;
	private File localGitDir;

	public static final File LOCALTEMP_DIR = new File(System.getProperty("java.io.tmpdir"), "p2mGitRepo");
	static {
		if (!LOCALTEMP_DIR.exists()) {
			LOCALTEMP_DIR.mkdirs();
		}
	}

	private FileRepositoryBuilder fileRepositoryBuilder = new FileRepositoryBuilder();

	public P2MGitClient(String remoteGitUrl) throws Exception {
		this(remoteGitUrl, null, null);
	}

	public P2MGitClient(String remoteGitUrl, String branch, File localGitDir) throws Exception {
		this.remoteGitUrl = remoteGitUrl;
		if (localGitDir == null) {
			String projectName = remoteGitUrl.substring(remoteGitUrl.lastIndexOf("/"), remoteGitUrl.indexOf(".git"));
			localGitDir = new File(LOCALTEMP_DIR, projectName);
		}
		this.localGitDir = localGitDir;

		this.branch = branch;
	}

	public void cloneToLocal() throws Exception {
		File gitFile = new File(localGitDir, ".git");
		if (localGitDir.exists() && gitFile.exists() && gitFile.isDirectory()) {
			pull();
		} else {
			clone(null, null);
		}

	}

	public void clone(String username, String password) throws Exception {
		CloneCommand cloneCommand = Git.cloneRepository();
		cloneCommand.setBare(false);
		if (isEmpty(this.branch)) {
			cloneCommand.setCloneAllBranches(true);
		} else {
			cloneCommand.setBranch(this.branch);
		}
		cloneCommand.setDirectory(this.localGitDir).setURI(this.remoteGitUrl);
		if (!isEmpty(username) && !isEmpty(password)) {
			cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
		}

		cloneCommand.call();
	}

	public File getLocalDirectory() {
		return localGitDir;
	}

	public void pull() throws IOException {
		Repository repository = fileRepositoryBuilder.setGitDir(this.localGitDir).readEnvironment().findGitDir()
				.build();
		Git git = new Git(repository);
		git.pull();
	}

	private static boolean isEmpty(String str) {
		return (str == null || str.length() < 1);
	}

}
